package cn.kgc.javaweb.dao.impl;

import cn.kgc.javaweb.dao.UserDao;
import cn.kgc.javaweb.entity.User;
import cn.kgc.javaweb.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: mosin
 * @version: v1.0  2022/10/30
 */
public class UserDaoImpl implements UserDao {

    @Override
    public User selectUser(User user) {  //  JDBC
        /**
         *  2. 根据用户传递的参数  查询数据库
         *  username +  password   ->  user   ->  true   -> 登录成功
         *  java 操作数据库  JDBC
         *  步骤:
         *   1. 导包
         *   2. 注册驱动  反射
         *   3. 获取连接
         *   4. 获取发送sql语句的对象 statement
         *   5. 发送sql
         *   6. 处理结果集  （select）
         *   7. 关闭连接 释放资源
         */
        User usr = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = DruidUtil.getConnection();
            String sql ="select *  from user  where username  = ? and  password = ?";
            // 预编译  提高sql语句的执行效率
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,user.getUsername() );
            preparedStatement.setString(2,user.getPassword() );

            // 结果集
            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()){

                int id = resultSet.getInt("id");
                String uname = resultSet.getString("username");
                String pwd = resultSet.getString("password");
                String address = resultSet.getString("address");
                usr = User.builder().password(pwd).username(uname).address(address).id(id).build();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.closeAll(resultSet, preparedStatement, connection);
        }

        return usr;
    }

    @Override
    public Integer addUser(User user) {  //  JDBCs

        return null;
    }
}
